import { createRouter, createWebHistory } from 'vue-router'
import AdminLayout from '../views/admin/layout/AdminLayout.vue'

const adminRouter = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/admin/login',
      name: 'AdminLogin',
      component: () => import('../views/admin/Login.vue'),
      meta: {
        title: '后台登录'
      }
    },
    {
      path: '/admin',
      component: AdminLayout,
      children: [
        {
          path: '',
          redirect: '/admin/tools/list',
          children: [
            {
              path: 'tools',
              name: 'ToolsManage',
              meta: {
                title: '工具管理',
                icon: 'Tools'
              },
              children: [
                {
                  path: 'category',
                  name: 'ToolCategory',
                  component: () => import('../views/admin/tools/Category.vue'),
                  meta: {
                    title: '工具分类'
                  }
                },
                {
                  path: 'list',
                  name: 'ToolList',
                  component: () => import('../views/admin/tools/List.vue'),
                  meta: {
                    title: '工具列表'
                  }
                }
              ]
            },
            {
              path: 'users',
              name: 'UsersManage',
              component: () => import('../views/admin/user/User.vue'),
              meta: {
                title: '用户管理',
                icon: 'User'
              }
            },
            {
              path: 'settings',
              name: 'Settings',
              component: () => import('../views/admin/settings/Index.vue'),
              meta: {
                title: '网站设置',
                icon: 'Setting'
              }
            }
          ]
        },
        {
          path: '/admin/:pathMatch(.*)*',
          name: 'AdminNotFound',
          component: () => import('../views/admin/NotFound.vue'),
          meta: {
            title: '页面未找到'
          }
        }
      ]
    }
  ]
})

// 全局路由守卫
adminRouter.beforeEach((to, from, next) => {
  // 获取管理员登录令牌
  const token = localStorage.getItem('admin_token')
  // 如果访问的不是登录页且没有令牌，重定向到登录页
  if (to.path !== '/admin/login' && !token) {
    next('/admin/login')
  } else {
    next()
  }
})

// 导出路由实例
export default adminRouter 